package main.java.indi.zyj.hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _05_threeSum {

    //定义三个指针，保证遍历数组中的每一个结果
    //画图，解答
    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> res = new ArrayList<>();
        int length = nums.length;

        if (nums == null || length < 3) {
            return res;
        }

        Arrays.sort(nums);

        for (int i = 0; i < length - 1; i++) {

            if (nums[i] > 0) {
                break;
            }

            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int left = i + 1, right = length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    while (left < right && nums[left + 1] == nums[left]){
                        left++;
                    }
                    while (left < right && nums[right - 1] == nums[right]){
                        right--;
                    }
                    left++;
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }

        }

        return res;

    }

}
